// 从axios框架导入axios组件
import axios from "axios";
import { getTokenName, removeToken } from "../util/util.js";
import { ElMessageBox } from "element-plus";

// 创建 axios 实例，并设置 baseURL
const axiosInstance = axios.create({
    baseURL: "http://localhost:8089", // 接口前缀
});

export function doGet(url, params) {
    return axiosInstance.get(url, { params });
}

export function doPost(url, data) {
    return axiosInstance.post(url, data);
}

export function doPut(url, data) {
    return axiosInstance.put(url, data);
}

export function doDelete(url, params) {
    return axiosInstance.delete(url, { params });
}

// 添加请求拦截器
axiosInstance.interceptors.request.use((config) => {
    const token = window.sessionStorage.getItem(getTokenName()) || window.localStorage.getItem(getTokenName());
    if (token) {
        config.headers['Authorization'] = token;
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

// 添加响应拦截器
axiosInstance.interceptors.response.use((response) => {
    if (response.data.code > 900) { // code大于900说明token验证未通过
        ElMessageBox.confirm(response.data.msg + "，是否重新登录？")
            .then(() => {
                removeToken(); // 删除有问题的token
                window.location.href = "/"; // 跳转到登录页
            })
            .catch(() => {
                console.warn("取消去登录");
            });
        return;
    }
    return response;
}, (error) => {
    return Promise.reject(error);
});
